package com.ylxl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylxl.common.constant.UserConstants;
import com.ylxl.common.domain.SysUser;
import com.ylxl.common.exception.BaseException;
import com.ylxl.common.utils.SecurityUtils;
import com.ylxl.common.utils.StringUtils;
import com.ylxl.entity.*;
import com.ylxl.entity.request.*;
import com.ylxl.mapper.SysUserMapper;
import com.ylxl.service.IAreasService;
import com.ylxl.service.ICityesService;
import com.ylxl.service.IPrivincesService;
import com.ylxl.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, User>  implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    private static List<China> chinaList = new ArrayList<>();

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private IPrivincesService privincesService;
    @Autowired
    private ICityesService cityesService;
    @Autowired
    private IAreasService areasService;



    @Override
    public List<User> selectUserList(QueryUser queryUser){
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper
                .like(StringUtils.isNotEmpty(queryUser.getName()), User::getName,queryUser.getName())
                .or().like(StringUtils.isNotEmpty(queryUser.getName()),User::getPhone,queryUser.getName());
        return userMapper.selectList(userLambdaQueryWrapper);
    }

    @Override
    public List<China> selectAddress() {
        //集合为空就是赋值。不为空从内存中取值
        if(CollectionUtil.isEmpty(chinaList)){
            QueryChina queryChina = new QueryChina();

            List<Privinces> privinces = privincesService.selectList(queryChina);
            List<Cities> cities = cityesService.selectList(queryChina);
            List<Areas> areas = areasService.selectList(queryChina);

            Map<String, List<Cities>> cityMap = cities.stream().collect(Collectors.groupingBy(Cities::getProvinceCode));
            privinces.forEach(p->{
                China china = new China(p);
                List<Cities> citiesList = cityMap.getOrDefault(p.getProvinceCode(), new ArrayList<>());
                Map<String, List<Areas>> areasMap = areas.stream().collect(Collectors.groupingBy(Areas::getCityCode));
                citiesList.forEach(c->{
                    List<Areas> areasList = areasMap.getOrDefault(c.getCityCode(),new ArrayList<>());
                    c.setAreasList(areasList);
                });
                china.setChildren(citiesList.stream().map(China.Two::new).collect(Collectors.toList()));
                chinaList.add(china);
            });

        }
        return chinaList;
    }

    @Override
    public boolean checkUserNameUnique(UserCmdOrMdy user){
        if(StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword()) ){
            throw new BaseException("用户名或密码不能为空");
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(StringUtils.isNotEmpty(user.getUserName()), User::getUserName,user.getUserName())
                        .ne(StringUtils.isNotEmpty(user.getId()), User::getId,user.getId());
        List<User> gardens = userMapper.selectList(userLambdaQueryWrapper);
        if(CollectionUtil.isNotEmpty(gardens)){
            return UserConstants.UNIQUE;
        }
        return UserConstants.NOT_UNIQUE;
    }

    @Override
    public int insertUser(UserCmdOrMdy user) {
        User userInsert = new User();
        BeanUtil.copyProperties(user, userInsert);//属性拷贝
        userInsert.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return userMapper.insert(userInsert);
    }

    @Override
    public int updateUser(UserCmdOrMdy user) {
        if(StringUtils.isEmpty(user.getId())){
            throw new BaseException("用户id不能为空");
        }
        User userUpdate = new User();
        BeanUtil.copyProperties(user, userUpdate);//属性拷贝
        userUpdate.setPassword(null);
        return userMapper.updateById(userUpdate);
    }

    @Override
    public SysUser selectUserByUserName(String userName) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(StringUtils.isNotEmpty(userName), User::getUserName,userName);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        SysUser sysUser = null;
        if(Objects.nonNull(user)){
            sysUser = new SysUser();
            sysUser.setUserName(user.getUserName());
            sysUser.setPassword(user.getPassword());
        }
        return sysUser;
    }

    @Override
    public User selctById(Integer id) {
        if(StringUtils.isEmpty(id)){
            throw new BaseException("id不能为空");
        }
        return userMapper.selectById(id);
    }

    @Override
    public int deleteByIds(List<Integer> ids) {
        return userMapper.deleteBatchIds(ids);
    }

    @Override
    public int enableOrDisable(UserStatusRequest userStatusRequest) {
        if(StringUtils.isEmpty(userStatusRequest.getId())){
            throw new BaseException("用户id不能为空");
        }
        User userUpdate = new User();
        BeanUtil.copyProperties(userStatusRequest, userUpdate);//属性拷贝
        return userMapper.updateById(userUpdate);
    }

    @Override
    public int changePassword(UserPasswordMdy userPasswordMdy) {
        if(StringUtils.isEmpty(userPasswordMdy.getId())){
            throw new BaseException("用户id不能为空");
        }
        User userUpdate = new User();
        userUpdate.setId(userPasswordMdy.getId());
        userUpdate.setPassword(SecurityUtils.encryptPassword(userPasswordMdy.getPassword()));
        return userMapper.updateById(userUpdate);
    }
}
